<template>
  <div class="addData content">
    <div class="header">
      <span class="title">序列列表</span>
      <div class="handle-bottom">
        <el-button size="small" :icon="Download" @click="download"
          >下载上传模版</el-button
        >
        <el-button
          :icon="Delete"
          style="margin-left: 10px"
          size="small"
          @click="delAll"
          :disabled=" isEdit && isStopOrOn"
          >一键清空</el-button
        >
        <el-upload
          ref="uploadFileRef"
          class="upload-file"
          accept=".xlsx"
          action="/api/anno/task/series/import"
          :data=" isCreate ? null : { taskId: projectId }"
          :headers="{ 'x-auth-token': token }"
          :on-success="handleSuccess"
          :on-error="onError"
          :disabled=" isEdit && isStopOrOn"
        >
          <el-button size="small" type="primary" :icon="Plus"
            >上传影像序列</el-button
          >
        </el-upload>
        <!-- <el-button style="margin-left:10px" size="small" @click="delAll" :disabled="isStopOrOn">删除</el-button> -->
      </div>
    </div>
    <div class="table-content">
<!--      <el-checkbox
        class="checkedAll"
        :disabled=" isEdit && isStopOrOn"
        :indeterminate="isIndeterminate"
        v-model="checkedAll"
        @change="checkedAllChange"
      ></el-checkbox>-->
      <el-table
        :data="tableData"
        style="width: 100%"
        stripe
        :class="tableData.length == 0 ? 'el-table-empty' : ''"
        @sort-change="sortChange"
        ref="table"
      >
        <!-- <el-table-column label="" width="55">
          <template #default="scope"> -->
        <!-- element ui 提供的多选功能不知道为什么只能全选不能全不选(取消), 这里自己模拟多选功能 -->
        <!-- <el-checkbox
              v-model="scope.row.checked" 
              @change="checkboxChange(scope.$index, scope.row)"
              :disabled="isStopOrOn"
            ></el-checkbox>
          </template>
        </el-table-column> -->

        <el-table-column type="index" width="140" label="序号" />

        <el-table-column label="序列号" width="1064">
          <template #default="scope">
            <p class="overflow-ellipsis" :title="scope.row.seriesUid">
              {{ scope.row.seriesUid }}
            </p>
          </template>
        </el-table-column>

        <el-table-column label="操作" fixed="right">
          <template #default="scope">
            <div class="handle">
              <el-button
                class="remove"
                size="mini"
                :disabled=" isEdit && isStopOrOn"
                @click="del(scope.$index, scope.row)"
                >删除</el-button
              >
            </div>
          </template>
        </el-table-column>

        <template slot="empty">
          <Empty></Empty>
        </template>
      </el-table>

      <el-pagination
        v-show="tableData.length > 0"
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="prev, pager, next, sizes"
        :total="total"
      >
      </el-pagination>
    </div>

  </div>
</template>

<script lang="ts">
  // @ts-nocheck
  import bus from '@/utils/bus';
  import { PageType, taskStatus, Step  } from '@/utils/emun';
  import { getUrlParams } from '@/utils/window';
  // import AddMaskImage from "./component/addMaskImage.vue";
  // import ImportMaskResult from "./component/importMaskResult.vue";
  import { getLocalStorage, setLocalStorage } from '@/utils/storage';
  import moment from 'moment';
  import { Gender, ProjectStatus } from '@/utils/emun';
  import Empty from '@/components/Empty/Empty.vue';
  import Scrollbar from '@/components/scrollbar/scrollbar.vue';
  import { Download, Delete, Plus } from '@element-plus/icons-vue';
  
  import { ElMessage } from 'element-plus';
  // import {
  //   seriesExport,
  //   projectCreate,
  //   projectEetailV2,
  //   projectUpdate,
  //   getImportResultList,
  // } from "@/http/labelProjectDetail";

  import { getToken } from '@/utils/auth';
  import {
    seriesImport,
    annoTask,
    taskUpdate,
  } from '@/api/projectDetail/projectDetail';
  import { setDraft, getDraft } from '@/utils/draft';

  export default {
    components: {
      Empty,
      Scrollbar,
    },
    data() {
      const { projectId, projectStatus } = getUrlParams();
      return {
        Download,
        Delete,
        Plus,
        projectStatus: projectStatus ? Number(projectStatus) : null,
        pageType:
          projectId && projectId.length === 16
            ? PageType.create
            : PageType.edit,
        moment,
        Gender,
        
        projectId,
        importMaskResultVisible: false,
        seriesImgFileType: '', //布局 数据类型
        tableDataAll: [],
        //      seriesUid				String	Y
        // 辅助/配准序列号		auxSeriesList				List(String)	N	 auxSeriess
        // 大图标注区域		annoAreaList				List(String)	N	  annoAreas
        tableData: [],
        currentPage: 1,
        total: 0,
        pageSize: 10,
        token: getToken(),
        selectionList: [],
        checked: false,

        resultModel: {
          page: 1,
          pageSize: 10,
          projectId: projectId,
          taskId: null,
        },
        viewResultVisible: false,
        resultList: [],
        resultListPages: 0,
        resultListTotal: 0,

        typeList: {
          1: '序列标注结果',
          2: '影像标注结果',
          3: '影像分割结果',
        },
        dataTypeList: {
          1: 'nii',
          2: '点位',
          3: 'mpr',
          4: '算法预处理',
        },
        currentindex: 0,
        multipleSelection: [],
        checkedAll: false,
        isIndeterminate: false,
        sortTag: '',
        studyDateClassName: false,
        uploadTimeClassName: false,
      };
    },
    computed: {
      isCreate() {
        return this.pageType === PageType.create;
      },
      isEdit() {
        return this.pageType === PageType.edit;
      },
      isView() {
        return this.pageType === PageType.view;
      },
      // 进行中
      isOn() {
        return taskStatus.way === this.projectStatus;
      },
      // 未发布
      isOff() {
        return taskStatus.off === this.projectStatus;
      },
      // 已完成
      isFinish(){
        return taskStatus.finish === this.projectStatus;
      },
      // 已终结
      isStop(){
        return taskStatus.end === this.projectStatus;
      },
      // 进行中 或者 已终结
      isStopOrOn(){
        return this.isOn || this.isStop;
      }
    },
    watch: {
      tableDataAll: {
        handler(model) {
          setDraft(this.projectId, 'dataSetting', model);
        },
        deep: true,
      },
    },

    async created() {
      this.init();
      bus.off('labelProject.' + Step.addData);
      bus.on('labelProject.' + Step.addData, async () => {
        bus.emit('labelProject.valid');
      });

      bus.off(`labelProject.editSave.${Step.addData}`);
      bus.on(`labelProject.editSave.${Step.addData}`, this.editSave);
    },
    methods: {
      onError() {},
      async init() {
        if (this.isCreate) {
          const tableDataAll = getDraft(this.projectId, 'dataSetting');
          if (tableDataAll) {
            tableDataAll.forEach((item) => (item.visible = false));
            this.tableDataAll = tableDataAll;
            this.setCurrentTableData();
          }
        }

        if (this.isEdit) {
          const res = (await annoTask(this.projectId)).data;
          const draftModel =
            getDraft(this.projectId, 'dataSetting') || res.dataInfo.seriesList;
          if (draftModel) {
            draftModel.forEach((item) => (item.visible = false));
            this.tableDataAll = draftModel;
            this.setCurrentTableData();
          }
        }
      },
      // 编辑状态下 保存
      async editSave() {
        const currnetModel = this.getModel();
        const projectConfigModel = this.getProjectConfigModel();
        const model = {
          ...currnetModel,
          ...projectConfigModel,
          id:this.projectId,
        }
        await taskUpdate(model);
        bus.emit('labelProject.goCreated');
      },
      getModel() {
        const { dataSetting, projectConfigModel, seriesFcListTableData, annoUserSetting } = getDraft(this.projectId) || {
          dataSetting: [],
        };
        // 添加数据
        const _dataSetting = {
          annoSeriesList:  ( dataSetting || [] ).map(item=>{
              return {
                seriesUid: item.seriesUid, //序列号
                auxSeriesList: item.auxSeriesList || [], //辅助/配准序列号
                annoAreaList: item.annoAreaList || [], //大图标注区域
              }
          })
        };
        const model = {
          dataSetting: _dataSetting,
          projectConfigModel,
          seriesFcListTableData,
          annoUserSetting
        };
        return model;
      },
      getProjectConfigModel(){
        const {
          projectConfigModel,
          seriesFcListTableData,
        } = getDraft(this.projectId) || {
          projectConfigModel:{},
          seriesFcListTableData: []
        };
        // 基本信息
        const basicSetting = {   
          name: projectConfigModel.name, //任务名称
          department: projectConfigModel.department, //科室
          label: projectConfigModel.label, //任务标签
          target: projectConfigModel.target, //任务目标
          uses: projectConfigModel.uses, //任务用途
          discardCode: projectConfigModel.discardCode ? projectConfigModel.discardCode.join(",") : "", // 废片原因 以,分隔
        };
        // 标注信息
        const annoSetting = {
            defaultWindow: projectConfigModel.defaultWindow,      //默认窗宽窗位
            findings: projectConfigModel.findings,        //是否展示检查所见
            diagnosis: projectConfigModel.diagnosis,       //是否展示诊断所得
            showYay: projectConfigModel.showYay,         //是否需要阴阳性
            showReport: projectConfigModel.showReport,       //是否需要图文报告
            imageLayout: projectConfigModel.imageLayout,        //布局
            seriesFcList: (seriesFcListTableData || []).map(item=> {
              return {
                fcId: item.id || item.fcId,
                required: item.required,
              }
            }),
            lesionList: ( projectConfigModel?.lesionList || [] ).map(item=> {
              return {
                lesionValue: item.lesionValue,      //病灶编码
                color: item.color,            //颜色
                toolValueList: item.toolValueList,    //工具编码列表
                imageFcList: ( item.imageFcListData || []).map(subItem=> {
                  return {
                    fcId: subItem?.id || subItem?.fcId || subItem,
                    required: subItem?.required || false,
                  }
                }),
                bizType: item.bizType,
              }
            })
        }
        const model = {
          basicSetting,
          annoSetting,
        }
        return model;
      },
      //全选
      checkedAllChange(checked) {
        this.tableDataAll.forEach((item) => {
          item.checked = checked;
        });
        this.isIndeterminate = false;
        this.setCurrentTableData();
      },
      checkboxChange() {
        if (this.tableDataAll.length == 0) {
          this.checkedAll = false;
          this.isIndeterminate = false;
          return;
        }
        this.checkedAll = this.tableDataAll.every((item) => item.checked);
        const multipleSelection = this.tableDataAll.filter(
          (item) => item.checked
        );
        this.isIndeterminate =
          multipleSelection.length > 0 &&
          multipleSelection.length < this.tableDataAll.length;
      },
      //全部删除
      delAll() {
        this.tableDataAll = [];
        this.setCurrentTableData();
        ElMessage({
          message: `已删除`,
        });
        //   const multipleSelection = this.tableDataAll.filter(item=> item.checked);
        //   if( multipleSelection.length == 0 ) {
        //     return this.$message({
        //       message: `请选择`,
        //     });
        //   }
        //   let list = this.tableDataAll.filter(item=> !item.checked);
        //   this.tableDataAll = list;
        //   this.setCurrentTableData();
        //   this.$message({
        //     message: `已删除`,
        //   });
      },
      isValidTableData() {
        return (
          Array.isArray(this.tableData) &&
          this.tableData.length > 0 &&
          !!this.tableData[this.currentindex]
        );
      },
      //手动对表格排序
      sortChange({ order, prop }) {
        //这里需要调用table组件本身的clearSort方法，因为手动排序和table组件本身的排序会冲突，导致数据错乱
        this.$refs.table.clearSort();
        if (this.sortTag === 'ascending') {
          this.tableDataAll.sort(
            (a, b) => this.toggleDate(b[prop]) - this.toggleDate(a[prop])
          );
          this.sortTag = 'descending';
        } else {
          this.tableDataAll.sort(
            (a, b) => this.toggleDate(a[prop]) - this.toggleDate(b[prop])
          );
          this.sortTag = 'ascending';
        }
        if (prop === 'studyDate') {
          this.studyDateClassName = true;
          this.uploadTimeClassName = false;
        }
        if (prop === 'uploadTime') {
          this.studyDateClassName = false;
          this.uploadTimeClassName = true;
        }
        this.setCurrentTableData();
      },
      toggleDate(date) {
        return typeof date === 'string' ? new Date(date).getTime() : date;
      },

      //表格当前行的标注结果同步给表格的其他行
      confirmAsync(row) {
        this.tableDataAll.forEach((item) => {
          if (row.isAsync) {
            if (item.assigned) return;
            const { taskId } =
              row.resultTasks.find((taskItem) => taskItem.selected) || {};
            const task = item.resultTasks.find(
              (subItem) => subItem.taskId === taskId
            );
            if (task) {
              item.resultTasks.forEach((taskItem) => {
                taskItem.selected = taskItem.taskId == taskId;
              });
            }
          }
          item.visible = false;
        });
        this.setCurrentTableData();
      },
      //选择标注结果
      selectResultTasks(row, taskIndex) {
        const index = this.tableDataAll.findIndex(
          (item) => item.seriesUid === row.seriesUid
        );
        this.tableDataAll[index].resultTasks.forEach((taskItem, _taskIndex) => {
          taskItem.selected = _taskIndex == taskIndex;
        });
        this.setCurrentTableData();
      },
      //删除
      del(index, item) {
        // if( this.isEdit && item.assigned ){
        //   return ElMessage.error("不允许移除已被任务引用的序列");
        // }
        const startNumber = (this.currentPage - 1) * this.pageSize + index;
        this.tableDataAll.splice(startNumber, 1);
        this.setCurrentTableData();
        ElMessage({
          message: `已删除`,
        });
      },
      // 上传影像序列
      async handleSuccess(res) {
        // const res = await seriesImport();
        const { code, data, msg } = res;
        if (code === 200) {
          this.handleTableData(data.seriesInfoList, true);
        } else {
          ElMessage.error(msg);
        }
      },
      // 对表格数据进行处理
      handleTableData(seriesInfoList, isUpdate) {
        //对表格数据去重
        const currentSeriesList = [];
        seriesInfoList.forEach(item=> {
          const index = currentSeriesList.findIndex(subItem=> subItem.seriesUid === item.seriesUid);
          if( index === -1 ){
            currentSeriesList.push(item);
          }
        });

        const addList = []; //新增
        const repeatList = []; //重复
        const list = this.tableDataAndField(currentSeriesList);
        list.forEach((item) => {
          const index = this.tableDataAll.findIndex(
            (subItem) => subItem.seriesUid === item.seriesUid
          );
          if (index > -1) {
            repeatList.push(item);
          } else {
            //新增
            addList.push(item);
          }
        });
        this.tableDataAll.push(...addList);
        if (isUpdate) {
          setTimeout(() => {
            ElMessage({
              showClose: true,
              message: `新增${addList.length}个、重复${repeatList.length}个(未导入)`,
              duration: 10000,
            });
          }, 0);
        }
        this.setCurrentTableData();
      },
      /*
      表格的分页是前端做的，所有表格数据存储在tableDataAll对象，当前页的数据储存在tableData对象
      对表格的任何操作都需要调用此方法来更新ui
      涉及到表格长度的操作，比如删除、新增，需要更新this.total的值，来保证分页页码正确。
    */
      setCurrentTableData() {
        const tableDataAll = this.tableDataAll;
        this.total = tableDataAll.length;
        const currentPage = Math.ceil(
          (tableDataAll.length || 1) / this.pageSize
        );
        const page = Math.min(currentPage, this.currentPage);
        const startIndex = (page - 1) * this.pageSize;
        const endIndex = startIndex + this.pageSize;
        const tableData = tableDataAll.slice(startIndex, endIndex);
        // .log(page, startIndex, endIndex, tableData.map(item=> item.seriesUid));
        this.tableData = tableData;
        this.currentPage = page;
        this.checkboxChange();
      },
      //为了操作数据的方便，给表格添加一些字段
      tableDataAndField(list) {
        list.forEach((item) => {
          item.visible = false;
          item.isActive = false;
          item.isAsync = false;
          item.checked = false;
          item.styleObject = {};
          const { resultTasks } = item;
          if (Array.isArray(resultTasks) && resultTasks.length) {
            resultTasks.forEach((subItem) => {
              subItem.name = subItem.projectId + '-' + subItem.taskId;
            });
            const otherRefer = {
              projectId: 0,
              taskId: 0,
              name: '不引用',
              selected: true,
            };
            item.resultTasks.push(otherRefer);
          } else {
            item.resultTasks = [
              {
                projectId: 0,
                taskId: 0,
                name: '无',
                selected: true,
              },
            ];
          }
        });
        return list;
      },
      handleSizeChange(pageSize) {
        this.pageSize = pageSize;
        this.setCurrentTableData();
      },
      handleCurrentChange(currentPage) {
        this.currentPage = currentPage;
        this.setCurrentTableData();
      },
      download() {
        const a = document.createElement('a');
        const url = '/static/序列导入模板.xlsx';
        a.href = url;
        a.download = '序列导入模板.xlsx';
        a.click();
      },
      async getImportResultList() {
        // const res = await getImportResultList(this.resultModel);
        // this.resultList = res.list;
        // this.resultListPages = res.pages;
        // this.resultListTotal = res.total;
        // this.viewResultVisible = true;
        return [];
      },
      async downloadSeries() {
        const model = {
          projectId: this.projectId,
        };
        const param = encodeURIComponent(JSON.stringify(model));
        const url = `${location.origin}/aaa/v1/project/series/auxiliary_series/export?param=${param}&accessToken=${this.accessToken}`;
        window.open(url, '_blank');
      },
      exportSeriesSuccess(res, file) {
        const { code, data, msg } = res;
        if (code === 0) {
          this.$message.success('上传成功');
        } else {
          this.$message.error(msg);
        }
      },
      confirmAddMaskIamge(values) {
        this.selectionList = values;
      },
      cancelImportMaskResult() {
        this.importMaskResultVisible = false;
      },
    },
  };
</script>

<style lang="less">
  .addData {
    .handle-bottom {
      display: flex;
    }

    .el-pagination {
      text-align: right;
    }

    .header {
      display: flex;
      justify-content: space-between;
      margin: 0 32px;
      margin-bottom: 15px;
      border-top: 1px solid #e8e8e8;
      padding-top: 25px;
      .title {
        font-weight: 700;
        font-size: 16px;
        color: #333333;
      }
      .el-dropdown {
        margin-right: 10px;
      }
    }
    .table-content {
      padding: 0 32px;
      .checkedAll {
        position: absolute;
        left: 58px;
        margin-top: 26px;
      }
      .el-table {
        .el-table__header-wrapper,
        .el-table__fixed-header-wrapper {
          thead {
            tr th {
              background: #fafafa;
            }
          }
        }
        tr.hover-row > td.el-table__cell {
          background-color: #ecf3f4;
        }
        .el-table__body-wrapper {
          tr td {
            background: #fff;
          }
          tr:last-child td {
            border: none;
          }
        }
        .handle {
          .el-button {
            border: none;
            background-color: transparent;
            &::hover {
              background-color: transparent;
            }
            span {
              color: #448e97;
            }
          }
          .remove:hover span {
            text-decoration: underline;
          }
        }
      }
    }

    .el-table__row.hover-row {
      td {
        background: #ecf3f4 !important;
      }
    }
    .el-table__fixed-right::before,
    .el-table__fixed::before {
      display: none;
    }
  }

  .upload-file {
    margin-left: 10px;
    .el-upload-list {
      display: none;
    }
  }

  .upload-file-series {
    .el-upload-list {
      display: none;
    }
  }

  .resultTasks {
    width: 270px;
    background: #ffffff;
    border: 1px solid #e8e8e8;
    box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.08);
    border-radius: 4px;
    .list {
      width: 100%;
      height: 100%;
      .item {
        font-style: normal;
        font-weight: 400;
        font-size: 14px;
        line-height: 18px;
        padding: 9px 12px;
        box-sizing: border-box;
        text-align: left;
        cursor: pointer;
        &.active {
          background: #f0f9fa;
          color: #448e97;
        }
        &:hover {
          background: #f0f9fa;
        }
      }
    }
    .select {
      border-top: 1px solid #e8e8e8;
      padding: 6px 8px;
      box-sizing: border-box;
      display: flex;
      justify-content: space-between;
      .el-checkbox {
        display: flex;
        align-items: center;
      }
    }
  }

  .resultTasks-el-popover {
    max-width: 120px;
  }

  .button-container {
    background: #ffffff;
    border: 1px solid #e8e8e8;
    border-radius: 2px;
    padding: 7px 8px 7px 12px;
    cursor: pointer;
    display: flex;
    align-items: center;
    position: relative;
    .refResultTaskName {
      min-width: 58px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      text-align: left;
      margin-right: 5px;
    }
    .el-icon-arrow-up {
      position: absolute;
      right: 10px;
      z-index: 2;
    }
    .el-icon-arrow-down {
      position: absolute;
      right: 10px;
      z-index: 2;
    }
    &.active {
      border: 1px solid #448e97;
    }
  }
  .el-popover {
    padding: 0;
  }

  .resultTasks {
    width: 270px;
    height: 225px;
    position: fixed;
    z-index: 200;
    .result-scrollbar {
      .scrollbar {
        height: 180px;
      }
    }
  }

  .el-table.el-table-empty {
    .el-table__empty-block {
      width: 100% !important;
    }
    .el-table__empty-text {
      width: auto;
    }
    &::before {
      display: none;
    }
  }

  .el-table-column--selection .cell {
    padding-left: 10px;
  }
  .el-table {
    .studyDate-column-ascending {
      .sort-caret.ascending {
        border-bottom-color: #448e97;
      }
    }
    .studyDate-column-descending {
      .sort-caret.descending {
        border-top-color: #448e97;
      }
    }
    .uploadTime-column-ascending {
      .sort-caret.ascending {
        border-bottom-color: #448e97;
      }
    }
    .uploadTime-column-descending {
      .sort-caret.descending {
        border-top-color: #448e97;
      }
    }
  }
</style>
